package domain.controller;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.data.QnAPersistenceManager;
import domain.model.Domain;
import domain.service.AgeDomain;
import domain.service.AlexaUpdate;
import domain.service.CheckDomain;
import domain.service.CheckRobotSitemap;
import domain.service.GooglePageRank;
import domain.service.Ip;
import domain.service.SelfSiteUpdate;

@SuppressWarnings("serial")
public class InsertDomainServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.getWriter().println("Hello, world");
        PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
        String showsite = req.getParameter("showsite");
        String title_url = req.getParameter("name").toLowerCase().replaceAll("(http|https)+://(www.)*", "").replaceAll("^[\\w\\W]+[\\/]{2}", "").replaceAll("[\\/]+[\\w\\W]+$", "").replaceAll("www.", "");
        if(title_url != null && title_url.length() > 0)
        {
        	Query query = psm.newQuery(Domain.class);
    		query.setFilter("name=='"+title_url+"'");
    		@SuppressWarnings("unchecked")
    		List<Domain> domains = (List<Domain>) query.execute();
    		if(domains.size()<=0)
    		{
    			if(CheckDomain.CheckDomain(title_url))
    			{
    				Domain domain = new Domain();
    				domain.setName(title_url);
    				if(showsite != null && showsite.equals("showsite"))
    				{
    					domain.setShowsite(1);
    				}
    				psm.makePersistent(domain);
    			} else {
    				resp.getWriter().println("Domain "+title_url+" does not exit");
    			}
    		}
        }
    }

}
